import {
  Injectable,
  ConflictException,
  UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import {
  CreateUserDto,
  UpdateUserDto,
  LoginUserDto,
  UserResponseDto,
} from './user.dto';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { AvatarUploadService } from '../common/services/avatar-upload.service';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    private jwtService: JwtService,
    private readonly avatarUploadService: AvatarUploadService,
  ) {}

  async createUser(createUserDto: CreateUserDto): Promise<UserResponseDto> {
    const { username, email, password } = createUserDto;

    // 检查用户名是否已存在
    const existingUsername = await this.userRepository.findOne({
      where: { username },
    });
    if (existingUsername) {
      throw new ConflictException('用户名已存在');
    }

    // 检查邮箱是否已存在
    const existingEmail = await this.userRepository.findOne({
      where: { email },
    });
    if (existingEmail) {
      throw new ConflictException('邮箱已被注册');
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const user = this.userRepository.create({
      username,
      email,
      password: hashedPassword,
    });

    await this.userRepository.save(user);

    // 返回用户信息（不包含密码）
    return this.mapUserToResponseDto(user);
  }

  async findAllUsers(): Promise<UserResponseDto[]> {
    const users = await this.userRepository.find();
    return users.map((user) => this.mapUserToResponseDto(user));
  }

  async findUserById(id: number): Promise<UserResponseDto> {
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    return this.mapUserToResponseDto(user);
  }

  async updateUser(
    id: number,
    updateUserDto: UpdateUserDto,
  ): Promise<UserResponseDto> {
    console.log(id, 55552);
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }

    // 如果更新密码，需要加密
    if (updateUserDto.password) {
      updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
    }

    // 更新用户信息
    Object.assign(user, updateUserDto);
    await this.userRepository.save(user);

    return this.mapUserToResponseDto(user);
  }

  async deleteUser(id: number): Promise<void> {
    const result = await this.userRepository.delete(id);
    console.log(id, 55553);
    if (result.affected === 0) {
      throw new UnauthorizedException('用户不存在');
    }
  }

  async login(loginUserDto: LoginUserDto): Promise<{ access_token: string }> {
    const { username, password } = loginUserDto;
    const user = await this.userRepository.findOne({
      where: { email: username },
    });
    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    // 生成JWT令牌
    const payload = { sub: user.id, username: user.username };
    const accessToken = this.jwtService.sign(payload);

    return { access_token: accessToken };
  }

  private mapUserToResponseDto(user: User): UserResponseDto {
    const { id, username, email, avatar, bio, isAdmin, createdAt, updatedAt } =
      user;
    return {
      id,
      username,
      email,
      avatar,
      bio,
      isAdmin,
      createdAt,
      updatedAt,
    };
  }

  // 获取当前登录用户信息
  async getCurrentUser(userId: number): Promise<UserResponseDto> {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    return this.mapUserToResponseDto(user);
  }

  // 退出登录
  async logout(): Promise<void> {
    // 在JWT认证系统中，退出登录主要由客户端完成（删除token）
    // 这里可以添加任何额外的服务端逻辑，如记录退出日志等
    return Promise.resolve();
  }

  // 上传用户头像
  async uploadUserAvatar(
    id: number,
    file: Express.Multer.File,
  ): Promise<{ avatarUrl: string }> {
    // 查找用户
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }

    // 如果用户已有头像，先删除旧头像
    if (user.avatar) {
      try {
        await this.avatarUploadService.deleteOldAvatar(user.avatar);
      } catch (error) {
        // 删除旧头像失败不影响新头像上传
        console.warn('删除旧头像文件失败:', error.message);
      }
    }

    // 保存新头像并获取URL
    const avatarUrl = await this.avatarUploadService.saveAvatar(file);

    // 更新用户的头像URL
    user.avatar = avatarUrl;
    await this.userRepository.save(user);

    return { avatarUrl };
  }
}
